<template>
  <div class="base-container" id="main">
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <div>
      <!-- 基本信息 -->
      <t-form ref="form" class="step-form" :data="formData" @submit="onSubmit" :rules="rules" labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-card class="step-card" size="medium" title="基本信息">
            <t-row style="align-items: stretch" :gutter="14">
              <t-col :span="6">
                <t-form-item label="工作室名称：" name="name">
                  <t-input style="width: 390px" placeholder="请输入工作室名称" clearable v-model="formData.name"
                  ></t-input>
                </t-form-item>
                <t-form-item label="级别" name="level">
                  <t-select style="width: 390px" clearable v-model="formData.level"
                            :options="dict.type.innovation_studio_level">
                  </t-select>
                </t-form-item>
                <t-form-item label="承担单位：" name="companyId">
                  <t-tree-select ref="select" clearable filterable style="width: 390px" :treeProps="{ keys: { value: 'id' } }"
                                 v-model="formData.companyId" :data="deptMenuOptions" placeholder="选择承担单位"></t-tree-select>
                </t-form-item>
                <t-form-item label="负责人：" name="leaderName">
                  <t-input style="width: 390px" placeholder="请输入负责人" clearable v-model="formData.leaderName"></t-input>
                </t-form-item>
                <t-form-item label="联系方式：" name="phone">
                  <t-input style="width: 390px" placeholder="请输入联系方式" clearable v-model="formData.phone"></t-input>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item label="地址：" name="address">
                  <t-input style="width: 390px" placeholder="请输入地址" clearable v-model="formData.address"></t-input>
                </t-form-item>
                <t-form-item label="邮编：" name="postCode">
                  <t-input style="width: 390px" placeholder="请输入邮编" clearable v-model="formData.postCode"></t-input>
                </t-form-item>
                <t-form-item label="成立时间：" name="buildDate">
                  <t-date-picker placeholder="请选择成立时间" v-model="formData.buildDate" style="width: 390px"></t-date-picker>
                </t-form-item>
              </t-col>
            </t-row>
          </t-card>
          </t-col>
        </t-row>
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item label="简介：" label-align="top" a name="content">
              <tiny-mce-editor :maxlength="2000"
                               v-model="formData.content"></tiny-mce-editor>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item label="每年的效益：" label-align="top"  name="studioBenefits">
              <studioBenefits ref="studioBenefits" :edit-open="true" v-model="formData.studioBenefits" :value="[]"></studioBenefits>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="12" class="query-form-inline">
              <t-button :loading="subBtnLoading" theme="primary" @click="subType=2"  type="submit">提交</t-button>
          </t-col>
        </t-row>
      </t-form>
    </div>
  </div>
</template>

<script>
import { getDictList } from "@/api/system/dict/data";
import {getFiles} from "@/api/common";
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";
import studioBenefits from "@/pages/tjpt/platform/components/studioBenefits.vue";
import { TODAY } from '@/utils/date';
import dayjs from "dayjs";
import {getIdCardBirthday} from "@/utils/common";


export default {
  name: "innovation-studio-apply",
  components: {
    TinyMceEditor,
    studioBenefits
  },
  dicts: ["formulate_type","standard_category","standard_property","innovation_studio_level"],
  data() {
    return {
      isEdit:false,
      profTitOptions:[],
      deptMenuOptions:[],
      dictTypes: {},
      nameOptions:[],
      leaderLoading:false,
      subBtnLoading:false,
      reviseNumDisable:true,
      active:1,
      subType:2,
      applyLoading: false,
      maxlength: 1000,
      lengthLimitObj: {
        description: 0
      },
      tinymceFlag: 1,
      dayjs,
      formData: {
        name:"",
        companyId:"",
        holdCompany:"",
        leaderName:"",
        phone:"",
        address:"",
        postCode:"",
        buildDate:"",
        studioBenefits:[],
        content:"",
        level:""
      },
      rules:{
        name: [
          {
            required: true,
            message: "工作室名称不能为空",
          },
        ],
        level:
          [
            {
              required: true,
              message: "级别不能为空",
            },
          ],
        companyId: [
          {
            required: true,
            message: "承担单位不能为空",
          },
        ],
        leaderName: [
          {
            required: true,
            message: "负责人不能为空",
          },
        ],
        phone: [
          {
            required: true,
            message: "联系方式不能为空",
          },
        ],
        address: [
          {
            required: true,
            message: "地址不能为空",
          },
        ],
        postCode: [
          {
            required: true,
            message: "邮编时间不能为空",
          },
        ],
        buildDate: [
          {
            required: true,
            message: "成立时间不能为空",
          },
        ],
        content: [
          {
            required: true,
            message: "简介不能为空",
          },
        ],
        studioBenefits: [
          {
            required: true,
            message: "每年的效益不能为空",
          },
        ],
      }
    }
  },
  async mounted() {
    await this.getDataTypes()
    if(this.$route.query.title==="编辑创新工作室"){
      this.isEdit = true
    }
    if (this.$route.params.taskId) {
      this.$api.tjpt.innovation.get(this.$route.params.taskId).then(response => {
        if (response.data){
          this.formData = response.data
        }
      }).catch(e => {
        this.$message.error(e.toString())
      })
    }
  },
  async created() {
    await this.getDeptTreeSelect()
    // 判断路由有没有id传过来
    // 有id则是修改需要回显数据，无id则是新增
  },
  methods: {
    onProfTitIdChange(val, content) {
      this.formData.profTit = content.node.data.level;
    },
    getDataTypes() {
      return getDictList(["project_type", "subject_classification", "sys_user_sex", "prof_tit", "degree", "education", "duty", "platform_type", "expect_result_type"]).then(response => {
        this.dictTypes = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onIdCardChange(val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== "") {
        this.formData.birthDate = birthday.slice(0, 7);
      }
    },
    onLeaderNameChange(val,content) {
      console.log(val,content)
      const index = this.nameOptions.findIndex(val=>content?.option?.id === val.id)
      console.log(index)
      console.log( this.nameOptions)
      this.nameOptions[index].label= this.nameOptions[index].name;
      this.$set(this.nameOptions,index,this.nameOptions[index])
      // Object.assign(this.formData.projectLeader, content.option)
      const oldId = this.formData.id;
      this.formData = content.option || this.nameOptions[index]
      this.formData.id = oldId;
    },
    createProjectLeaderOptions(value){
      this.nameOptions.push({
        label:`${value}`,
        value,
        name: value
      });
    },
    remoteProjectLeaderMethod(search){
      this.leaderLoading = true;
      this.$api.system.member.searchList({name:search}).then(response => {
        this.nameOptions = response.data.map(val=>  ({
          ...val,
          label:`${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.leaderLoading = false;
      }).catch((e) => {
        this.leaderLoading = false;
        this.$message.error(e.toString());
      });
    },
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    filterByTree(val, tree, children = "children", id = "id", label = "label") {
      let text = '';
      const convert = (arr) => {
        arr.filter((item) => {
          if (item[id] === val) {
            text = item[label]
          } else if (item[children]) {
            return convert(item[children])
          }
          return false
        })
      }
      convert(tree)
      return text
    },
    close() {
      this.subBtnLoading = false;
      setTimeout(() => {
        this.$tab.closeOpenPage({path: this.$route.meta.activeMenu || "/tjpt/other/platform/innovation-studio-apply"});
        // this.$tab.closeOpenPage({path: "/tjpt/other/platform/innovation-studio-apply"});
      }, 1000)
    },
    onSubmit({ validateResult, firstError }) {
      if ( validateResult === true) {
        this.formData.holdCompany = this.filterByTree(this.formData.companyId, this.deptMenuOptions)
        // 路由有id修改，没有新增
        if (this.isEdit) {
          this.formData.id = this.$route.params.taskId
          const message = "编辑成功"
          this.subBtnLoading = true
          this.$api.tjpt.innovation.edit(this.formData).then(response => {
            this.subBtnLoading =false
            this.$message.success(message)
            this.$emit("reload")
            this.close();
            this.$router.push("/tjpt/platform/innovation-studio-my")
          }).catch(e => {
            this.subBtnLoading =false
            this.$message.error(e.toString())
          })
        } else {
          const message = "提交成功"
          this.subBtnLoading = true
          // this.formData.platformId = this.$route.params.id
          console.log("this.formData",this.formData)
          this.$api.tjpt.innovation.add(this.formData).then(response => {
            this.subBtnLoading =false
            this.$message.success(message)
            this.$emit("reload")
            this.close();
            this.$router.push("/tjpt/platform/innovation-studio-my")
          }).catch(e => {
            this.subBtnLoading =false
            this.$message.error(e.toString())
          })
        }
      } else {
        this.subBtnLoading =false
        this.$message.error(firstError)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>

